//
//  ScrollViewTableController.m
//  Tang
//
//  Created by 352324497@qq.com on 15/12/4.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "ScrollViewTableController.h"
#import "ScrollViewCellModel.h"
#import "ScrollViewTableCell.h"
#import "HomeDetailViewController.h"
@interface ScrollViewTableController ()
@property (nonatomic, strong)NSMutableArray *array;
@property (nonatomic, assign)NSInteger Num;
@end

@implementation ScrollViewTableController
-(NSMutableArray *)array
{
    if (!_array)
    {
        self.array = [NSMutableArray array];
    }
    return _array;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.Num = 0;
    self.navigationItem.title = self.name;
    self.tableView.separatorStyle = NO;
    
    // 判断是否是从搜索界面跳转过来的
    if (self.isCategory == NO)
    {
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            NSString *str = [self.extend stringByReplacingOccurrencesOfString:@"," withString:@"%2c"];
            NSString *url = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/list?app_installtime=1449053241.284786&app_versions=5.0&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&ids=%@&os_versions=9.1&page=0&pagesize=20&screensize=640&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=8",str];
            [self requestDataWithUrl:url];
            [self.tableView.mj_header endRefreshing];
        }];
        [self.tableView.mj_header beginRefreshing];
    }
    else
    {
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self.array removeAllObjects];
            NSString *url = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/list?app_installtime=1449053241.284786&app_versions=5.0.1&category=%@&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&os_versions=9.1&page=0&pagesize=20&screensize=640&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=8", self.ID];
            [self requestDataWithUrl:url];
            [self.tableView.mj_header endRefreshing];
        }];
        [self.tableView.mj_header beginRefreshing];
        
        self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
            self.Num += 1;
            NSString *url = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/list?app_installtime=1449053241.284786&app_versions=5.0.1&category=%@&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&os_versions=9.1&page=%ld&pagesize=20&screensize=640&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=8", self.ID, self.Num];
            [self requestDataWithUrl:url];
            [self.tableView.mj_footer endRefreshing];
        }];
    }
    

}

-(void)requestDataWithUrl:(NSString *)url
{
//    self.array = [NSMutableArray array];
    [[NetworkState shareInstance]reachablityStatesWithDongHua:self];
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            NSLog(@"请求数据失败");
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            [[NetworkState shareInstance] finshYYToVc:self];
            return ;
        }
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSDictionary *dataDic = Dic[@"data"];
        NSString *string = dataDic[@"today"];
        NSArray *arr = dataDic[@"topic"];
        for (NSDictionary *dic in arr)
        {
            ScrollViewCellModel *model = [[ScrollViewCellModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            model.today = string;
            [self.array addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [[NetworkState shareInstance]finshYYToVc:self];
        });
    }]resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.array.count != 0)
    {
        return self.array.count;
    };
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return KWidth * 330 / 620 + 80 * Kx6;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ScrollViewTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        cell = [[ScrollViewTableCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
    }
    if (self.array.count != 0)
    {
        ScrollViewCellModel *model = self.array[indexPath.row];
        cell.model = model;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ScrollViewTableCell *cell = (ScrollViewTableCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    HomeDetailViewController *homeDetailVc = [[HomeDetailViewController alloc]init];
    ScrollViewCellModel *model = self.array[indexPath.row];
    homeDetailVc.PinJieId = model.ID;
    homeDetailVc.headerImage = cell.picImageView.image;
    [self.navigationController pushViewController:homeDetailVc animated:NO];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
